package org.bonorsoft.modules.sysutils.redisutil;

import org.bonorsoft.common.constant.CacheConstant;
import org.bonorsoft.common.constant.CommonConstant;
import org.bonorsoft.common.util.RedisUtil;
import org.bonorsoft.modules.system.entity.SysUser;
import org.bonorsoft.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Component
public class RedisOperate {
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private  RedisUtil redisUtils;

    private static ISysUserService userService;

    private static  RedisUtil redisUtil;

    @PostConstruct
    public void init() {
        userService = sysUserService;
        redisUtil = redisUtils;
    }

    /**
     * 根据菜单id，获取该id下的所有用户，并删除redis中的缓存信息
     * @param menuId 菜单id
     */
    public static void delUserShiroByMenuId(Long menuId) {
        List<String> userIdLists =  userService.getAllMenuUser(menuId);
        delShiroByUserIds(userIdLists);

    }

    /**
     * 根据角色id，获取该id下的所有用户，并删除redis中的缓存信息
     * @param roleId 角色id
     */
    public static void delUserShiroByRoleId(String roleId) {
        List<String> userIdLists =  userService.getAllRoleUser(roleId);
        delShiroByUserIds(userIdLists);
    }

    /**
     * 根据用户ids删除redis中的缓存信息
     * @param userIdLists
     */
    private static void delShiroByUserIds(List<String> userIdLists) {
        int size = userIdLists.size();
        if(size != 0){
            final String[] userIds = new String[size];
            final int[] i = {0};
            userIdLists.forEach(item-> {
                userIds[i[0]] = CommonConstant.PREFIX_USER_SHIRO_CACHE + item;
                i[0]++;
            });
            redisUtil.del(userIds);
        }
    }

    public static void removeUser(SysUser sysUser) {
        redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
        redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, sysUser.getUsername()));
    }
}
